import re

def parse_txt(file_path):
    with open(file_path, 'r', encoding='gb18030') as file:
        content = file.read()

    # 分割题目类型部分
    sections = re.split(r'(单选题|多选题|判断题)\n', content)[1:]
    questions = []

    for i in range(0, len(sections), 2):
        if i == 0 and re.match(r'\w+题', sections[i]):
            current_type = sections[i]
            items = sections[i + 1].strip().split('\n')
        else:
            current_type = sections[i]
            items = sections[i + 1].strip().split('\n')

        # 重构为不同题型对应不同解析逻辑
        if current_type == "判断题":
            questions += parse_true_false_questions(items, current_type)
        elif current_type == "单选题":
            questions += parse_single_choice_questions(items, current_type)
        elif current_type == "多选题":
            questions += parse_multiple_choice_questions(items, current_type)
        else:
            break
    print(f"共解析出{len(questions)}道题")
    return questions

def parse_true_false_questions(items, current_type):
    """解析判断题（答案为正确/错误）"""
    questions = []
    index = 0
    while index < len(items):
        item = items[index]
        index += 1
        lines = item.strip().split('\n')
        # 提取题号和问题
        match = re.match(r'(\d+)\s*\.\s*(.*)', lines[0])
        if not match:
            continue
        number = int(match.group(1))
        question = match.group(2)

        # 提取答案（固定为正确/错误）
        answer = ""
        extra_question_text = ""
        while index < len(items):
            stripped_line = items[index].strip()
            index += 1
            if re.match(r'^(答案)?[:：]?(正确|错误).*$', stripped_line):
                answer = stripped_line.strip('答案:：。')
                break
            else:
                extra_question_text += stripped_line

        # 拼接问题文本
        question += extra_question_text.strip()

        # 提取解析
        explanation = ""
        tmp_index = index
        while tmp_index < len(items):
            stripped_line = items[tmp_index].strip()
            if stripped_line.startswith('解析'):
                explanation = stripped_line.split('解析')[1].strip().strip(':：')
                tmp_index += 1
                continue
            if re.match(r'^\d+', stripped_line):
                index = tmp_index
                break
            explanation += stripped_line
            tmp_index += 1

        # 将问题里面的空格都去掉
        question = question.replace(' ', '')
        answer = answer.strip().replace(' ', '')
        explanation = explanation.replace(' ', '')

        questions.append({
            '题目类型': current_type,
            '题号': number,
            '问题': question,
            '答案': answer,
            '解析': explanation
        })
    print(f"{current_type}共解析出{len(questions)}道题")
    return questions


def parse_single_choice_questions(items, current_type):
    """解析单选题（答案为选项字母，如A/B/C）"""
    questions = []
    index = 0
    while index < len(items):
        item = items[index]
        index += 1
        lines = item.strip().split('\n')

        match = re.match(r'(\d+)\s*\.\s*(.*)', lines[0])
        if not match:
            continue
        number = int(match.group(1))
        question = match.group(2)
        options = []  # 新增：存储选项

        # 提取选项（格式如"A. 选项内容"）
        answer = ''
        option_pattern = re.compile(r'^([A-Z])[.) ]\s*(.*)')
        while index < len(items):
            stripped_line = items[index].strip()
            index += 1
            # 匹配选项行
            option_match = option_pattern.match(stripped_line)
            if option_match:
                options.append({
                    'key': option_match.group(1),
                    'text': option_match.group(2)
                })
            # 遇到答案行则停止选项提取
            elif re.match(r'^(答案)?[:：]?\s*[A-Z]$', stripped_line):
                answer = stripped_line.strip('答案:：')
                break
            # 特殊答案特殊处理
            #   268 .在设计用户中心时，应该遵循( )原则来提高用户体验。
            #         A.保持一致性
            #         B.减少操作步骤
            #         C.使用复杂的界面设计
            #         D.提供个性化推荐
            #   答案：ABD
            #   解析：A保持一致性可以让用户操作更熟悉和流畅；B减少操作步骤能提高效率和用户体验
            #         ； D提供个性化推荐可以满足不同用户的需求，都有助于提高用户体验。C使用复杂的界
            #         面设计会增加用户的学习成本和操作难度， 降低用户体验。
            #         A——如果只能是一个答案，建议这个
            elif stripped_line=='答案：ABD':
                answer = 'A'
                break
            # 非选项行视为问题扩展文本
            else:
                question += stripped_line

        # 提取解析（逻辑同判断题）
        explanation = ""
        tmp_index = index
        while tmp_index < len(items):
            stripped_line = items[tmp_index].strip()
            if stripped_line.startswith('解析'):
                explanation = stripped_line.split('解析')[1].strip().strip(':：')
                tmp_index += 1
                continue
            if re.match(r'^\d+', stripped_line):
                index = tmp_index
                break
            explanation += stripped_line
            tmp_index += 1

        # 将问题里面的空格都去掉
        question = question.replace(' ', '')
        answer = answer.strip().replace(' ', '')
        explanation = explanation.replace(' ', '')

        questions.append({
            '题目类型': current_type,
            '题号': number,
            '问题': question.strip(),
            '选项': options,  # 新增选项字段
            '答案': answer,
            '解析': explanation
        })
    print(f"{current_type}共解析出{len(questions)}道题")
    return questions


def parse_multiple_choice_questions(items, current_type):
    """解析多选题（答案为多个选项字母，如AB/ABC）"""
    # 复用单选题解析逻辑，仅调整答案匹配正则
    questions = []
    index = 0
    while index < len(items):
        item = items[index]
        index += 1
        lines = item.strip().split('\n')
        match = re.match(r'(\d+)\s*\.\s*(.*)', lines[0])
        if not match:
            continue
        number = int(match.group(1))
        question = match.group(2)
        options = []

        answer = ''
        option_pattern = re.compile(r'^([A-Z])[.) ]\s*(.*)')
        while index < len(items):
            stripped_line = items[index].strip()
            index += 1
            option_match = option_pattern.match(stripped_line)
            if option_match:
                options.append({
                    'key': option_match.group(1),
                    'text': option_match.group(2)
                })
            # 匹配多选题答案（允许2-4个字母）
            elif re.match(r'^(答案)?\s*[:：]?\s*[A-Z]+$', stripped_line):
                answer = stripped_line.strip('答案:：')
                break
            else:
                question += stripped_line + ' '

        explanation = ""
        tmp_index = index
        while tmp_index < len(items):
            stripped_line = items[tmp_index].strip()
            if stripped_line.startswith('解析'):
                explanation = stripped_line.split('解析')[1].strip().strip(':：')
                tmp_index += 1
                continue
            if re.match(r'^\d+', stripped_line):
                index = tmp_index
                break
            explanation += stripped_line
            tmp_index += 1

        # 将问题里面的空格都去掉
        question = question.replace(' ', '')
        answer = answer.strip().replace(' ', '')
        explanation = explanation.replace(' ', '')

        questions.append({
            '题目类型': current_type,
            '题号': number,
            '问题': question.strip(),
            '选项': options,
            '答案': answer,
            '解析': explanation
        })
    print(f"{current_type}共解析出{len(questions)}道题")
    return questions
